1.2. Exploring the Newly Created Project 探索新项目
- 标准的管理配置文件 pom.xml
- 原文路径 src/main/java/
- 测试文件路径 src/test/java/
在原文路径下的com.example
包中有两个 class 文件,这个 Main 类主要是负责承接 Grizzly 容器,同时也为这个容器配置和部署 JAX-RS 应用。在同一个包内的另外一个类 MyResource 类是 JAX-RS 的一个实现的源代码,如下:
在src/test/java
目录下的 MyResourceTest 类是对 MyResource 的单元测试,他们具有相同的包com.example
package com.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.grizzly.http.server.HttpServer;
...
public class MyResourceTest {
private HttpServer server;
private WebTarget target;
@Before
public void setUp() throws Exception {
server = Main.startServer();
Client c = ClientBuilder.newClient();
target = c.target(Main.BASE_URI);
}
@After
public void tearDown() throws Exception {
server.stop();
}
/**
* Test to see that the message "Got it!" is sent in the response.
*/
@Test
public void testGetIt() {
String responseMsg = target.path("myresource").request().get(String.class);
assertEquals("Got it!", responseMsg);
}
在testgetit()方法中,JAX-RS 客户端 API 是用来连接并发送 HTTP GET 请求的 MyResource JAX-RS 资源类侦听在/myresource
的URI。同样作为 JAX-RS API 方法调用链的一部分,回应以Java字符串类型被读到。在测试方法的第二行,响应的内容(从服务器返回的字符串)跟测试断言预期短语比较(译者注:即方法)。要了解更多有关使用 JAX-RS 客户端API,请参阅第5章客户端API。